from helper import *

class mxd_helper(geo_helper):
	def __init__(self):
		geo_helper.__init__(self)
		self.desc = ['country', 'region', 'city', 'postalCode',\
			'metroCode' ,'areaCode']
		self.locid = None
		self.ir = [[1,-1, GL_COUNTRY], [2,-1, GL_STATE], \
			[3,-1, GL_CITY], [4,-1, GL_POSTCODE], \
			[7,-1, GL_METROCODE], [8,-1, GL_AREACODE]]
		self.cir = []
	
	def realname(self, name):
		return s.strip(' "\t\r\n')
		
	def readloc(self, line, ir):
		rec = line.split(',')
		if len(rec) < 3:
			return False
		try:
			id = int(rec[0])
			rg = []
			coord = (rec[5], rec[6])
			for n, d, flag in ir:
				name = self.realname(rec[n])
				desc = ''
				if d != -1:
					desc = self.realname(rec[d])
				rg.append([name, desc, flag])
			self.locid[id] = [rg, coord]
			return True
		except (IndexError, ValueError):
			return False
	
	def	readblock(self, line):
		self.loc.clear()
		info = self.info
		rec = line.split(',')
		if len(rec) < 3:
			return False
		try:
			locid = self.realname(rec[2])
			id = int(locid)
			if not id in self.locid:
				return False
			rg, coord = self.locid[id]
			for n, d, flag in rg:
				info.loc.append([n, d, flag, 0, None])
			self.range = (self.realname(rec[0]), self.realname(rec[1]))
			self.coord = coord
			return True
		except (IndexError, ValueError):
			return False
	
	def loadloc(self, locfile, ir):
		count = 0
		fp = open(locfile, 'r')
		if fp:
			try:
				for line in fp:
					if readloc(self, line, ir):
						count += 1
			finally:
				fp.close()
		return count
	
	def wizard(self, locfile = None):
		if locfile:
			self.loadloc(self, locfile, self.cir)
	
	def learn(self, line):
		return self.readloc(line, self.ir)
	def read(self, line):
		return self.readblock(line)

class mxd_helper_cli(mxd_helper):
	def __init__(self):
		mxd_helper.__init__(self)

